#include "CustomerSystem.h"
#include <limits>
#include <cstdlib>

void Product::increaseStock(int amount)
{
    if (amount > 0)
    {
        stock += amount;
    }
}
// =============== System 类 ===============

void System::loadCustomers()
{
    // 从文件中读,ifstream类似cin
    ifstream file(DATA_C_FILE);
    if (!file)
        return;

    string u, p, n;
    while (file >> u >> p >> n)
    {
        // 通过key->value
        customers[u] = Customer(u, p, n);
    }
    file.close();
}

void System::saveCustomers()
{
    // 向文件中写Customer对象
    ofstream file(DATA_C_FILE);
    for (const auto &pair : customers)
    {
        const Customer &c = pair.second; // Customer对象
        file << c.getUsername() << " " << c.getPassword() << " "
             << c.getName() << " "
             << "\n"; // 简化存储
    }
    file.close();
}

void System::loadProducts()
{
    ifstream file(DATA_P_FILE);
    if (!file)
    {
        cerr << "警告：无法打开商品文件，将创建空列表" << endl; // 添加错误提示
        return;
    }

    string category, name, description;
    double price;
    int stock;
    while (file >> category >> name >> price >> stock)
    {
        getline(file, description);
        description.erase(0, 1); // 去掉开头的空格
        products[name] = Product(category, name, price, description, stock);
    }
    file.close();
}

void System::saveProducts()
{
    ofstream file(DATA_P_FILE);
    for (const auto &pair : products)
    {
        const Product &p = pair.second;
        file << p.getCategory() << " " << p.getName() << " " << p.getPrice() << " " << p.getStock() << " " << p.getDescription() << "\n";
    }
    file.close();
}

void System::run()
{
    mainMenu();
}

void System::adminLogin()
{
    string username, password;
    cout << "请输入管理员账户名: ";
    cin >> username;
    cout << "请输入管理员密码: ";
    cin >> password;
    if (admin.login(username, password))
    {
        cout << "管理员登录成功！" << endl;
        adminMenu();
    }
    else
    {
        cout << "管理员登录失败，请检查账户名和密码！" << endl;
    }
}

// void System::adminMenu()
// {
//     while (true)
//     {
//         cout << "\n管理员菜单:" << endl;
//         cout << "1. 管理商品信息" << endl;
//         cout << "2. 退出登录" << endl;
//         cout << "请输入您的选择: ";
//         int choice;
//         cin >> choice;
//         switch (choice)
//         {
//         case 1:
//             manageProducts();
//             break;
//         case 2:
//             cout << "管理员已退出登录！" << endl;
//             return;
//         default:
//             cout << "无效的选择，请重新输入！" << endl;
//         }
//     }
// }
void System::adminMenu()
{
    while (true)
    {
        cout << "\n管理员菜单:" << endl;
        cout << "1. 管理商品信息" << endl;
        cout << "2. 管理订单" << endl; // 添加管理订单选项
        cout << "3. 退出登录" << endl;
        cout << "请输入您的选择: ";

        int choice;
        cin >> choice;
        switch (choice)
        {
        case 1:
            manageProducts();
            break;
        case 2:
            // manageOrders(); // 调用管理订单函数
            break;
        case 3:
            cout << "管理员已退出登录！" << endl;
            return;
        default:
            cout << "无效的选择，请重新输入！" << endl;
        }
    }
}
void System::customerMenu(Customer &customer)
{
    while (true)
    {
        cout << "\n顾客菜单:" << endl;
        cout << "1. 查看商品信息" << endl;
        cout << "2. 从商品列表购买" << endl;
        cout << "3. 修改密码" << endl;
        cout << "4. 退出登录" << endl;
        cout << "5. 查询商品信息" << endl;
        cout << "6. 添加商品到购物车" << endl;
        cout << "7. 从购物车删除商品" << endl;
        cout << "8. 修改购物车商品数量" << endl;
        cout << "9. 查看购物车" << endl;
        cout << "10. 从购物车购买" << endl;
        cout << "11. 查看我的订单" << endl;
        cout << "12. 修改订单" << endl;
        cout << "13. 删除订单" << endl;
        cout << "请输入您的选择: ";
        
        int choice;
        cin >> choice;
        switch (choice)
        {
        case 1:
            displayProducts();
            break;
        case 2:
            purchaseFromProductList(customer);
            break;
        case 3:
        {
            string oldPwd, newPwd;
            cout << "请输入旧密码: ";
            cin >> oldPwd;
            cout << "请输入新密码: ";
            cin >> newPwd;
            if (customer.changePassword(oldPwd, newPwd))
            {
                cout << "密码修改成功！" << endl;
                saveCustomers();
            }
            else
            {
                cout << "旧密码输入错误，密码修改失败！" << endl;
            }
            break;
        }
        case 4:
            cout << "顾客已退出登录！" << endl;
            return;
        case 5:
            searchProducts();
            break;
        case 6:
            addToCart(customer);
            break;
        case 7:
            removeFromCart(customer);
            break;
        case 8:
            modifyCart(customer);
            break;
        case 9:
            viewCart(customer);
            break;
        case 10:
            purchaseFromCart(customer);
            break;
        case 11:
            viewOrders(customer);
            break;
        case 12:
            modifyOrder(customer);
            break;
        case 13:
            deleteOrder(customer);
            break;
        default:
            cout << "无效的选择，请重新输入！" << endl;
        }

        // 每次操作后自动更新订单状态
        orderList.updateOrderStatuses();
    }
}

void System::customerLogin()
{
    string username, password;
    cout << "请输入顾客账户名(uid): ";
    cin >> username;
    cout << "请输入顾客密码: ";
    cin >> password;
    auto it = customers.find(username); // 在map中找是否有，返回一个迭代器
    if (it != customers.end() && it->second.getPassword() == password)
    {
        cout << "顾客登录成功！" << endl;
        customerMenu(it->second);
        // key是string类型的用户名，value是customer类型的对象
    }
    else
    {
        cout << "顾客登录失败，请检查账户名和密码！" << endl;
    }
}

void System::customerRegister()
{
    string username;
    cout << "请输入要注册的账户名: ";
    cin >> username;
    if (customers.find(username) != customers.end())
    {
        cout << "该账户名已存在，请选择其他账户名！" << endl;
        return;
    }
    string password;
    cout << "请输入密码: ";
    cin >> password;
    string name;
    cout << "请输入您的姓名: ";
    cin >> name;
    // k找v！
    customers[username] = Customer(username, password, name);
    saveCustomers();
    cout << "注册成功！" << endl;
}

void System::manageProducts()

{
    while (true)
    {
        cout << "\n商品管理菜单:" << endl;
        cout << "1. 查看商品列表" << endl;
        cout << "2. 添加商品" << endl;
        cout << "3. 修改商品信息" << endl;
        cout << "4. 删除商品" << endl;
        cout << "5. 退出商品管理" << endl;
        cout << "请输入您的选择: ";
        int choice;
        cin >> choice;
        switch (choice)
        {
        case 1:
            displayProducts();
            break;
        case 2:
            addProduct();
            break;
        case 3:
            modifyProduct();
            break;
        case 4:
            deleteProduct();
            break;
        case 5:
            return;
        default:
            cout << "无效的选择，请重新输入！" << endl;
        }
    }
}

void System::displayProducts() const
{
    cout << "\n商品列表:" << endl;
    for (const auto &pair : products)
    {
        const Product &product = pair.second;
        cout << "类别: " << product.getCategory()
             << ", 名称: " << product.getName()
             << ", 价格: " << product.getPrice()
             << ", 库存: " << product.getStock() << endl;
    }

    // 添加以下代码暂停输出
    cout << "\n按回车键返回主菜单/或进行后续操作...";
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 清除之前残留的输入
    cin.get();                                           // 等待用户按回车
}

void System::addProduct()
{
    string category, name, description;
    double price;
    int stock;
    cout << "请输入商品类别: ";
    cin >> category;
    cout << "请输入商品名称: ";
    cin >> name;
    cout << "请输入商品价格: ";
    cin >> price;
    cout << "请输入商品描述: ";
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    getline(cin, description);
    cout << "请输入商品库存: ";
    cin >> stock;
    products[name] = Product(category, name, price, description, stock);
    saveProducts();
    cout << "商品添加成功！" << endl;
}

void System::modifyProduct()
{
    // 清除之前的输入残留
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string name;
    cout << "请输入要修改的商品名称: ";
    getline(cin, name);

    auto it = products.find(name);
    if (it == products.end())
    {
        cout << "该商品不存在！" << endl;
        return;
    }

    Product &product = it->second;
    string input;

    // 1. 修改商品类别
    cout << "请输入新的商品类别（留空则不修改）: ";
    getline(cin, input);
    if (!input.empty())
    {
        product.setCategory(input);
    }

    // 2. 修改商品价格
    cout << "请输入新的商品价格（留空则不修改）: ";
    getline(cin, input);
    if (!input.empty())
    {
        try
        {
            product.setPrice(stod(input));
        }
        catch (...)
        {
            cout << "无效的价格格式，保持原价" << endl;
        }
    }

    // 3. 修改商品描述
    cout << "请输入新的商品描述（留空则不修改）: ";
    getline(cin, input);
    if (!input.empty())
    {
        product.setDescription(input);
    }

    // 4. 修改商品库存
    cout << "请输入新的商品库存（留空则不修改）: ";
    getline(cin, input);
    if (!input.empty())
    {
        try
        {
            product.setStock(stoi(input));
        }
        catch (...)
        {
            cout << "无效的库存格式，保持原库存" << endl;
        }
    }

    saveProducts();
    cout << "商品信息修改成功！" << endl;
}

void System::deleteProduct()
{
    string name;
    cout << "请输入要删除的商品名称: ";
    cin >> name;
    auto it = products.find(name);
    if (it == products.end())
    {
        cout << "该商品不存在！" << endl;
        return;
    }
    products.erase(it);
    saveProducts();
    cout << "商品删除成功！" << endl;
}

void System::searchProducts()
{
    if (products.empty())
    {
        cout << "商品列表为空，请先添加商品！" << endl;
        return;
    }

    cin.clear(); // 清除错误状态
    string keyword;
    cout << "请输入查询关键字: ";

    // 确保清除之前的换行符
    if (cin.peek() == '\n')
        cin.ignore();
    getline(cin, keyword);

    // 空输入处理
    if (keyword.empty())
    {
        cout << "输入不能为空！" << endl;
        return;
    }

    bool found = false;
    for (const auto &pair : products)
    {
        const Product &p = pair.second;
        if (p.getName().find(keyword) != string::npos ||
            p.getCategory().find(keyword) != string::npos)
        {
            cout << "找到商品: " << p.getName() << endl;
            found = true;
        }
    }

    if (!found)
    {
        cout << "未找到匹配商品，尝试模糊搜索..." << endl;
        fuzzySearchProducts(keyword);
    }

    // 暂停
    cout << "\n按回车键返回主菜单...";
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

void System::fuzzySearchProducts(const string &keyword)
{
    cout << "未找到精确匹配的商品，以下是最接近的商品信息：" << endl;
    for (const auto &pair : products)
    {
        const Product &product = pair.second;
        if (product.getName().find(keyword) != string::npos || product.getCategory().find(keyword) != string::npos || product.getDescription().find(keyword) != string::npos)
        {
            cout << "类别: " << product.getCategory() << ", 名称: " << product.getName()
                 << ", 价格: " << product.getPrice()
                 << ", 描述: " << product.getDescription()
                 << ", 库存: " << product.getStock()
                 << endl;
        }
    }
}

void System::purchaseProduct(Customer &customer)
{
    displayProducts();
    string productName;
    cout << "请输入要购买的商品名称: ";
    cin >> productName;
    auto it = products.find(productName);
    if (it == products.end())
    {
        cout << "该商品不存在！" << endl;
        return;
    }
    int quantity;
    cout << "请输入要购买的数量: ";
    cin >> quantity;
    if (it->second.getStock() < quantity)
    {
        cout << "库存不足，购买失败！" << endl;
        return;
    }
    it->second.decreaseStock(quantity);
    saveProducts();
    cout << "购买成功！" << endl;
}

// void System::addToCart(Customer &customer)
// {
//     displayProducts();
//     string productName;
//     cout << "请输入要添加到购物车的商品名称: ";
//     cin >> productName;
//     auto it = products.find(productName);
//     if (it == products.end())
//     {
//         cout << "该商品不存在！" << endl;
//         return;
//     }
//     int quantity;
//     cout << "请输入要添加的数量: ";
//     cin >> quantity;
//     customer.getCart().addProduct(it->second, quantity);
// }
void System::addToCart(Customer &customer)
{
    displayProducts();
    string productName;
    cout << "请输入要添加到购物车的商品名称: ";
    cin >> productName;
    auto it = products.find(productName);
    if (it == products.end())
    {
        cout << "该商品不存在！" << endl;
        return;
    }
    int quantity;
    cout << "请输入要添加的数量: ";
    cin >> quantity;
    if (quantity > it->second.getStock())
    {
        cout << "库存不足，无法添加这么多商品到购物车。" << endl;
        return;
    }
    customer.getCart().addProduct(it->second, quantity);
}

void System::removeFromCart(Customer &customer)
{
    while (true)
    {
        customer.getCart().displayCart();
        cout << "\n请选择操作：" << endl;
        cout << "1. 删除单个商品" << endl;
        cout << "2. 删除全部商品" << endl;
        cout << "3. 返回" << endl;
        cout << "请输入选项: ";

        int choice;
        cin >> choice;
        cin.ignore(); // 清除缓冲区的换行符

        switch (choice)
        {
        case 1:
        {
            cout << "请输入要删除的商品名称: ";
            string productName;
            cin >> productName;
            customer.getCart().removeProduct(productName);
            break;
        }
        case 2:
        {
            cout << "确定要删除购物车中的所有商品吗？(y/n): ";
            char confirm;
            cin >> confirm;
            if (confirm == 'y' || confirm == 'Y')
            {
                customer.getCart().clearCart();
            }
            break;
        }
        case 3:
            return;
        default:
            cout << "无效选项，请重新输入！" << endl;
        }
    }
}
// void System::removeFromCart(Customer &customer)
// {
//     customer.getCart().displayCart();
//     string productName;
//     cout << "请输入要从购物车删除的商品名称: ";
//     cin >> productName;
//     customer.getCart().removeProduct(productName);
// }

// void System::modifyCart(Customer &customer)
// {
//     customer.getCart().displayCart();
//     string productName;
//     cout << "请输入要修改数量的商品名称: ";
//     cin >> productName;
//     int newQuantity;
//     cout << "请输入新的数量: ";
//     cin >> newQuantity;
//     customer.getCart().modifyQuantity(productName, newQuantity);
// }
void System::modifyCart(Customer &customer)
{
    customer.getCart().displayCart();
    string productName;
    cout << "请输入要修改数量的商品名称: ";
    cin >> productName;
    int newQuantity;
    cout << "请输入新的数量: ";
    cin >> newQuantity;

    auto productIt = products.find(productName);
    if (productIt != products.end())
    {
        if (newQuantity > productIt->second.getStock())
        {
            cout << "库存不足，无法将商品数量修改为 " << newQuantity << "。" << endl;
            return;
        }
    }

    customer.getCart().modifyQuantity(productName, newQuantity);
}

void System::viewCart(Customer &customer)
{
    customer.getCart().displayCart();
}

void System::mainMenu()
{
    while (true)
    {
        system("cls || clear");
        cout << "\n主菜单:" << endl;
        cout << "1. 管理员登录" << endl;
        cout << "2. 顾客登录" << endl;
        cout << "3. 顾客注册" << endl;
        cout << "4. 不登录查看商品列表" << endl;
        cout << "5. 不登录查询商品信息" << endl;
        cout << "6. 退出系统" << endl;
        cout << "请输入选项: ";
        int choice;
        cin >> choice;
        switch (choice)
        {
        case 1:
            adminLogin(); // 管理员登录
            break;
        case 2:
            customerLogin(); // 用户登录
            break;
        case 3:
            customerRegister(); // 用户注册
            break;
        case 4:
            displayProducts();
            break;
        case 5:
            searchProducts();
            break;
        case 6:
            cout << "系统已退出！" << endl;
            return;
        default:
            cout << "无效的选择，请重新输入！" << endl;
        }
    }
}

void System::purchaseFromProductList(Customer &customer)
{
    displayProducts();

    string productName;
    int quantity;
    cout << "请输入要购买的商品名称: ";
    cin >> productName;
    cout << "请输入购买数量: ";
    cin >> quantity;

    // 检查商品存在性和库存
    if (products.find(productName) == products.end())
    {
        cout << "商品不存在！" << endl;
        return;
    }

    if (products[productName].getStock() < quantity)
    {
        cout << "库存不足！" << endl;
        return;
    }

    // 收集收货地址
    string address;
    cin.ignore(); // 清除缓冲区
    cout << "请输入收货地址: ";
    getline(cin, address);

    // 创建订单
    unordered_map<string, int> items;
    items[productName] = quantity;

    string orderId = orderList.createOrder(customer, items, products, address);
    if (!orderId.empty())
    {
       //cout << "订单创建成功！订单编号: " << orderId << endl;
        cout << "订单创建成功！"<< endl;
    }
}

void System::purchaseFromCart(Customer &customer)
{
    customer.getCart().displayCart();

    if (customer.getCart().isEmpty())
    {
        cout << "购物车为空！" << endl;
        return;
    }

    // 收集收货地址
    string address;
    cin.ignore();
    cout << "请输入收货地址: ";
    getline(cin, address);

    // 从购物车创建订单
    string orderId = orderList.createOrder(
        customer,
        customer.getCart().getItems(),
        products,
        address);

    if (!orderId.empty())
    {
        cout << "订单创建成功！订单编号: " << orderId << endl;
    }
}

void System::viewOrders(Customer &customer)
{
    orderList.displayCustomerOrders(customer.getUsername());
}

void System::modifyOrder(Customer &customer)
{
    viewOrders(customer);

    string orderId;
    cout << "请输入要修改的订单编号: ";
    cin >> orderId;

    Order *order = orderList.findOrderById(orderId);
    if (!order || order->getCustomerUsername() != customer.getUsername())
    {
        cout << "订单不存在或无权访问！" << endl;
        return;
    }

    cout << "请选择操作: " << endl;
    cout << "1. 修改收货地址" << endl;
    cout << "2. 取消订单" << endl;
    int choice;
    cin >> choice;

    if (choice == 1)
    {
        string newAddress;
        cin.ignore();
        cout << "请输入新的收货地址: ";
        getline(cin, newAddress);
        if (order->updateAddress(newAddress))
        {
            cout << "地址更新成功！" << endl;
        }
    }
    else if (choice == 2)
    {
        if (order->cancelOrder(products))
        {
            cout << "订单已取消！" << endl;
        }
    }
}

void System::manageOrders()
{
    while (true)
    {
        cout << "\n===== 管理员订单管理 =====" << endl;
        cout << "1. 查看所有订单" << endl;
        cout << "2. 按客户查看订单" << endl;
        cout << "3. 修改订单状态" << endl;
        cout << "4. 删除订单" << endl;
        cout << "5. 返回" << endl;
        cout << "请输入您的选择: ";

        int choice;
        cin >> choice;
        cin.ignore(); // 清除输入缓冲区

        switch (choice)
        {
        case 1:
            // 显示所有订单
            cout << "\n===== 所有订单列表 =====" << endl;
            for (const auto &order : orderList.getCustomerOrders("")) // 空用户名表示所有订单
            {
                try
                {
                    order.displayOrderDetails();
                    cout << "----------------------------------------" << endl;
                }
                catch (const std::exception &e)
                {
                    cerr << "显示订单详情时出错: " << e.what() << endl;
                }
            }
            break;

        case 2:
            // 按客户查看订单
            {
                string username;
                cout << "请输入客户用户名: ";
                if (getline(cin, username))
                {
                    try
                    {
                        orderList.displayCustomerOrders(username);
                    }
                    catch (const std::exception &e)
                    {
                        cerr << "按客户查看订单时出错: " << e.what() << endl;
                    }
                }
                else
                {
                    cerr << "读取用户名输入失败" << endl;
                }
            }
            break;

        case 3:
            // 修改订单状态
            {
                string orderId, newStatus;
                cout << "请输入要修改的订单编号: ";
                if (cin >> orderId)
                {
                    cout << "请输入新的订单状态 (待发货/已发货/已签收): ";
                    if (cin >> newStatus)
                    {
                        try
                        {
                            if (orderList.manuallyUpdateStatus(orderId, newStatus))
                            {
                                cout << "订单状态更新成功！" << endl;
                            }
                            else
                            {
                                cout << "订单状态更新失败！" << endl;
                            }
                        }
                        catch (const std::exception &e)
                        {
                            cerr << "修改订单状态时出错: " << e.what() << endl;
                        }
                    }
                    else
                    {
                        cerr << "读取新订单状态输入失败" << endl;
                    }
                }
                else
                {
                    cerr << "读取订单编号输入失败" << endl;
                }
            }
            break;

        case 4:
            // 删除订单（需要客户信息）
            if (!customers.empty())
            {
                string customerUsername;
                cout << "请选择要删除订单的客户用户名: ";
                if (cin >> customerUsername)
                {
                    auto it = customers.find(customerUsername);
                    if (it != customers.end())
                    {
                        try
                        {
                            deleteOrder(it->second);
                        }
                        catch (const std::exception &e)
                        {
                            cerr << "删除订单时出错: " << e.what() << endl;
                        }
                    }
                    else
                    {
                        cout << "客户不存在！" << endl;
                    }
                }
                else
                {
                    cerr << "读取客户用户名输入失败" << endl;
                }
            }
            else
            {
                cout << "没有客户数据！" << endl;
            }
            break;

        case 5:
            return;

        default:
            cout << "无效的选择，请重新输入！" << endl;
        }
    }
}

void System::deleteOrder(Customer &customer)
{
    // 显示客户订单列表
    orderList.displayCustomerOrders(customer.getUsername());

    string orderId;
    cout << "请输入要删除的订单编号 (输入 'q' 返回): ";
    cin >> orderId;

    if (orderId == "q")
        return;

    // 查找订单
    Order *order = orderList.findOrderById(orderId);

    if (!order || order->getCustomerUsername() != customer.getUsername())
    {
        cout << "订单不存在或无权访问！" << endl;
        return;
    }

    // 检查订单状态（只能删除特定状态的订单）
    if (order->getStatus() != "已签收" && order->getStatus() != "已取消")
    {
        cout << "只能删除'已签收'或'已取消'状态的订单！" << endl;
        return;
    }

    // 确认删除
    cout << "确定要删除该订单吗？(y/n): ";
    char confirm;
    cin >> confirm;

    if (confirm == 'y' || confirm == 'Y')
    {
        if (orderList.removeOrder(orderId))
        {
            cout << "订单删除成功！" << endl;
        }
        else
        {
            cout << "订单删除失败！" << endl;
        }
    }
    else
    {
        cout << "订单删除已取消！" << endl;
    }
}

// =============== ShoppingCart 类 ===============

void ShoppingCart::clearCart()
{
    items.clear();
    productReferences.clear();
    cout << "购物车已清空！" << endl;
}
void ShoppingCart::addProduct(const Product &product, int quantity)
{
    if (items.find(product.getName()) != items.end())
    {
        cout << "商品已存在于购物车中，是否仍要加入（y/n）？";
        char choice;
        cin >> choice;
        if (choice == 'y' || choice == 'Y')
        {
            items[product.getName()] += quantity;
        }
    }
    else
    {
        items[product.getName()] = quantity;
        productReferences[product.getName()] = &product;
    }
}

void ShoppingCart::removeProduct(const string &productName)
{
    auto it = items.find(productName);
    if (it != items.end())
    {
        items.erase(it);
        productReferences.erase(productName);
        cout << "商品已从购物车中删除。" << endl;
    }
    else
    {
        cout << "购物车中不存在该商品。" << endl;
    }
}

void ShoppingCart::modifyQuantity(const string &productName, int newQuantity)
{
    auto it = items.find(productName);
    if (it != items.end())
    {
        const Product *product = productReferences.at(productName);
        if (newQuantity > product->getStock())
        {
            cout << "库存不足，无法将商品数量修改为 " << newQuantity << "。" << endl;
            return;
        }

        if (newQuantity == 0)
        {
            cout << "是否要删除该商品（y/n）？";
            char choice;
            cin >> choice;
            if (choice == 'y' || choice == 'Y')
            {
                items.erase(it);
                productReferences.erase(productName);
                cout << "商品已从购物车中删除。" << endl;
            }
        }
        else
        {
            it->second = newQuantity;
            cout << "商品数量已更新。" << endl;
        }
    }
    else
    {
        cout << "购物车中不存在该商品。" << endl;
    }
}

void ShoppingCart::displayCart() const
{
    cout << "\n购物车信息:" << endl;
    for (const auto &pair : items)
    {
        const Product *product = productReferences.at(pair.first);
        cout << "名称: " << product->getName()
             << ", 价格: " << product->getPrice()
             << ", 数量: " << pair.second
             << ", 小计: " << product->getPrice() * pair.second << endl;
    }
    cout << "商品总数: " << getTotalQuantity() << endl;
    cout << "总价格: " << getTotalPrice() << endl;
}

int ShoppingCart::getTotalQuantity() const
{
    int total = 0;
    for (const auto &pair : items)
    {
        total += pair.second;
    }
    return total;
}

double ShoppingCart::getTotalPrice() const
{
    double total = 0;
    for (const auto &pair : items)
    {
        const Product *product = productReferences.at(pair.first);
        total += product->getPrice() * pair.second;
    }
    return total;
}

// 判断购物车是否为空的函数定义
bool ShoppingCart::isEmpty() const
{
    return items.empty();
}

// 获取购物车中的商品及数量的函数定义
const unordered_map<string, int> &ShoppingCart::getItems() const
{
    return items;
}
//================OrderList===============================

//静态成员初始化
int OrderList::nextOrderId = 1;

vector<Order> &OrderList::getOrders()
{
    return orders;
}

bool OrderList::removeOrder(const string &orderId)
{
    auto it = find_if(orders.begin(), orders.end(),
                     [&](const Order &order)
                     { return order.getOrderId() == orderId; });

    if (it != orders.end())
    {
        orders.erase(it);
        return true;
    }
    return false;
}

// 创建新订单
string OrderList::createOrder(Customer &customer,
                            const unordered_map<string, int> &cartItems,
                            unordered_map<string, Product> &products,
                            const string &address)
{
    // 检查库存
    for (const auto &pair : cartItems)
    {
        if (products.find(pair.first) == products.end() ||
            products[pair.first].getStock() < pair.second)
        {
            cout << "库存不足，无法创建订单！" << endl;
            return "";
        }
    }

    // 生成唯一订单号
    string orderId = "ORD" + to_string(nextOrderId++);

    // 创建订单对象并添加到列表
    Order newOrder(orderId, customer.getUsername(), cartItems, products, address);
    orders.push_back(newOrder);

    // 更新库存
    for (const auto &pair : cartItems)
    {
        products[pair.first].decreaseStock(pair.second);
    }

    // 清空购物车
    customer.getCart().clearCart();

    cout << "订单创建成功！订单号：" << orderId << endl;
    return orderId;
}

// 查询订单
vector<Order> OrderList::getCustomerOrders(const string &username) const
{
    vector<Order> result;
    for (const auto &order : orders)
    {
        if (username.empty() || order.getCustomerUsername() == username)
        {
            result.push_back(order);
        }
    }
    return result;
}

Order *OrderList::findOrderById(const string &orderId)
{
    for (auto &order : orders)
    {
        if (order.getOrderId() == orderId)
        {
            return &order;
        }
    }
    return nullptr; // 未找到订单
}

// 订单状态管理
void OrderList::updateOrderStatuses()
{
    time_t currentTime = time(nullptr);

    for (auto &order : orders)
    {
        // 待发货 -> 已发货（10秒后自动转换）
        if (order.getStatus() == "待发货" &&
            difftime(currentTime, order.getCreateTime()) >= 10)
        {
            order.setStatus("已发货");
            cout << "订单 " << order.getOrderId() << " 状态已更新为：已发货" << endl;
        }
        // 已发货 -> 已签收（20秒后自动转换）
        else if (order.getStatus() == "已发货" &&
                 difftime(currentTime, order.getCreateTime()) >= 20)
        {
            order.setStatus("已签收");
            cout << "订单 " << order.getOrderId() << " 状态已更新为：已签收" << endl;
        }
    }
}

bool OrderList::manuallyUpdateStatus(const string &orderId, const string &newStatus)
{
    Order *order = findOrderById(orderId);
    if (!order)
    {
        cout << "订单不存在！" << endl;
        return false;
    }

    // 状态流转逻辑
    if ((order->getStatus() == "待发货" && newStatus == "已发货") ||
        (order->getStatus() == "已发货" && newStatus == "已签收"))
    {
        return order->setStatus(newStatus);
    }
    else
    {
        cout << "非法的状态转换：从 " << order->getStatus() << " 到 " << newStatus << endl;
        return false;
    }
}

// 显示订单
void OrderList::displayCustomerOrders(const string &username) const
{
    cout << "\n===== 客户 " << username << " 的订单列表 =====" << endl;
    bool hasOrders = false;

    for (const auto &order : orders)
    {
        if (username.empty() || order.getCustomerUsername() == username)
        {
            hasOrders = true;
            order.displayOrderDetails();
            cout << "----------------------------------------" << endl;
        }
    }

    if (!hasOrders)
    {
        cout << "您还没有任何订单！" << endl;
    }
}

//=================================Order=================================
// Order类成员函数实现
Order::Order(const string &id, const string &username,
             const unordered_map<string, int> &cartItems,
             const unordered_map<string, Product> &products,
             const string &addr)
    : orderId(id), customerUsername(username), address(addr)
{
    createTime = time(nullptr);
    status = "待发货";
    totalPrice = 0.0;
    // 复制购物车商品到订单
    for (const auto &pair : cartItems)
    {
        items[pair.first] = pair.second;
        totalPrice += products.at(pair.first).getPrice() * pair.second;
    }
}

bool Order::updateAddress(const string &newAddress)
{
    if (status != "待发货")
    {
        cout << "订单状态不是待发货，无法修改地址！" << endl;
        return false;
    }
    address = newAddress;
    return true;
}

bool Order::cancelOrder(unordered_map<string, Product> &products)
{
    if (status != "待发货")
    {
        cout << "订单状态不是待发货，无法取消！" << endl;
        return false;
    }
    // 恢复库存
    for (const auto &pair : items)
    {
        products[pair.first].increaseStock(pair.second);
    }
    status = "已取消";
    return true;
}

bool Order::setStatus(const string &newStatus)
{
    static const unordered_map<string, string> validNextStatus = {
        {"待发货", "已发货"},
        {"已发货", "已签收"}};
    
    // Use find() instead of operator[] since we're working with a const map
    auto it = validNextStatus.find(status);
    if (it != validNextStatus.end() && it->second == newStatus)
    {
        status = newStatus;
        return true;
    }
    cout << "不允许的状态转换：" << status << " → " << newStatus << endl;
    return false;
}

void Order::displayOrderDetails() const
{
    cout << "订单编号：" << orderId << endl;
    cout << "客户名称：" << customerUsername << endl;
    cout << "创建时间：" << ctime(&createTime);
    cout << "订单状态：" << status << endl;
    cout << "收货地址：" << address << endl;
    cout << "商品列表：" << endl;
    for (const auto &pair : items)
    {
        cout << "- " << pair.first << " × " << pair.second << endl;
    }
    cout << "订单总价：" << totalPrice << " 元" << endl;
}